package rs.networx.servlets;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.ejb.EJB;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.servlet.*;

import rs.networx.dao.PersonDao;
import rs.networx.entity.Person;
import rs.networx.util.ImageResizer;
import rs.networx.util.PropertiesUtil;

public class UploadProfilePictureServlet extends HttpServlet {

	private static final long serialVersionUID = -411784863275454548L;
	
	@EJB
	private PersonDao personDao;
	
	private String username;
	private String password;
	private Person loggedUser;
	
	private String fullFileName;
	private String extension;
	private String fileName;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
		System.out.println("LOADED UploadProfilePictureServlet");
		
		response.setContentType("text/html; charset=UTF-8");
		request.setCharacterEncoding(response.getCharacterEncoding());
		
		HttpSession session = request.getSession(true);
		
		loggedUser = (Person) session.getAttribute("logovaniUser");
		
		try {
			username = loggedUser.getEmail();
			password = loggedUser.getPassword();
			System.out.println(username + "  " + password);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
		
		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(2000000);
			
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setSizeMax(3000000);
			
			List<?> items = upload.parseRequest(request);
			Iterator<?> iter = items.iterator();
			
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				
				// constructing filename and extension...
				fullFileName = item.getName();
				System.out.println("Full fileName: " + fullFileName);
				
				extension = fullFileName.substring(fullFileName.lastIndexOf('.') + 1 ,
						fullFileName.length());
				
				// fileName to save in DB...
				fileName = loggedUser.getId() + "." + extension;
				System.out.println("FileName to save in DB: " + fileName);
				
				// saving picture in database...
				loggedUser.setPicture(fileName);
				personDao.merge(loggedUser);
				
				// making both pictures (fullsize and thunbnail) and saving them on server...
				saveProfilePictures(item, fileName, extension, request, response);
				
				response.sendRedirect("ViewSelectedPostsPage.jsp");
			}
		} catch (Exception ex) {
			//ex.printStackTrace();
			
			// obrada ako dodje do greske prilikom uploada slike...
			request.getRequestDispatcher("UploadPictureError.jsp").forward(request, response);
			return;
		}	
	}
		public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		doGet(request, response);
	}
	
	private void saveProfilePictures(FileItem fileItem, String fileName, String extension,
			HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		try {
			System.out.println("You have successfully upload the file: " + fileName);

			BufferedImage image = ImageIO.read(fileItem.getInputStream());

			String propertyFile = getServletContext().getRealPath("networx.properties");
			String networxDir = PropertiesUtil.getProperty(propertyFile, "networxDir");

			// saving image in full size...
			ImageIO.write(image, extension, new File(networxDir + "/profile/fullSize/" + fileName));

			// saving resized image...
			int y = 100;
			int x = 100 * image.getWidth() / image.getHeight();
			image = ImageResizer.createResizedCopy(image, x, y, true);			
			ImageIO.write(image, extension, new File(networxDir + "/profile/thumbnails/" + fileName));

			System.out.println("Succesculy made thumbnail for: " + fileName);
		} catch (Exception e) {
			//e.printStackTrace();
			
			// obrada ako dodje do greske prilikom uploada slike...
			//request.getRequestDispatcher("UploadPictureError.jsp").forward(request, response);
			//return;
		}
	}
	
	
}
